//
//  AppCheck.swift
//  EasyChat
//
//  Created by it-go-0367 on 2021/12/14.
//

import UIKit
import UserNotifications

/** APP相关内容的检查，诸如软件版本、硬件版本和相关权限等*/
class AppCheck: NSObject {
    
    public static let instance : AppCheck = AppCheck.init()
    /** 消息推送中心*/
    let notifyCenter : UNUserNotificationCenter = UNUserNotificationCenter.current()
    
    /** 检查APP的推送权限*/
    func notifyCheck() {
        //设置回调
        notifyCenter.delegate = self
        /// 取得用户授权 显示通知（上方提示条/声音/badgeNumber）
       if #available(iOS 10.0, *) {
           UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert, .carPlay]) { (success, error) in
               print("授权" + (success ? "成功" : "失败"))
           }
       } 
    }
    
    /** 简单即时消息的推送*/
    func pushCommonNotify(message : String, fromNumber : Int) {
        let content = UNMutableNotificationContent.init()
        let fromMate = AppDelegate.userInfos[fromNumber]!
        content.title = fromMate.mateName
        //content.badge = 1
        content.body = "\(fromMate.mateName):\(message)"
        
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.01, repeats: false)
        let request = UNNotificationRequest.init(identifier: "pushLocalNotify", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { error in
            //print("提交成功")
        }
    }
    
    /** 群组消息的推送*/
    func pushGroupNotify(message : String, groupID : Int, fromID : Int) {
        let content = UNMutableNotificationContent.init()
        let group = AppDelegate.groupInfos[groupID]!
        let mate = AppDelegate.userInfos[fromID]!
        content.title = group.groupName
        //content.badge = 1
        content.body = "\(mate.mateName):\(message)"
        
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.01, repeats: false)
        let request = UNNotificationRequest.init(identifier: "pushLocalNotify", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { error in
            //print("提交成功")
        }
    }
}
/** 消息推送的回调函数*/
extension AppCheck: UNUserNotificationCenterDelegate, UIApplicationDelegate {
    /** 消息将要推送过来的回调，可以选择消息的类型*/
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        /** 消息的类型
         * 1. alert 最普通的消息推送，解锁时位于屏幕顶端，未解锁则列表显示，IOS14后弃用
         * 2. list锁屏情况下列表消息推送，解锁情况下，不显式推送，IOS14启用
         * 3. badge无消息推送，仅显示应用小红点
         * 4. banner齐全的消息推送，类似于alert，IOS14后启用
         * 5. sound声音提醒
         */
        if #available(iOS 14.0, *) {
            completionHandler(.banner)
        } else {
            // Fallback on earlier versions
        }
    }
    
    /** 用户点击消息推送的触发事件*/
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("注册成功: ", deviceToken)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("注册失败: ", error)
    }
}
